此篇是使用BeautifulSoup抓取旅遊景點的延伸應用
建議可以先看過後再看這邊會比較有感覺
首先需要先載入csv套件
import requests
接下來定義要寫入csv的list
li_counter = []
定義要輸出的csv標頭
PATCH_COLUMNS = [
"Region",
"City",
"Viewpoint",
"tag"
]
在資料的最裡面增加以下的array,並放上相對應的資料
存到li_counter的list裡面
_counter = {}
_counter["Region"] = viewpoint.getText()
_counter["City"] = de_viewpoint.find("span",class_="circularbtn-title").getText()
_counter["Viewpoint"] = title.select_one("div", class_="card-title").getText()
_counter["tag"] = hashtag.getText()
print(" -"+hashtag.getText())
li_counter.append(_counter)
接下來寫入檔案,這要記得encoding不能使用UTF8,要使用utf-8-sig。不然會亂碼。
with open('viewpoint.csv', 'w', encoding='utf-8-sig', newline='') as f:
writer = csv.DictWriter(f, fieldnames=PATCH_COLUMNS)
writer.writeheader()
writer.writerows(li_counter)
最後打開匯出的viewpoint.csv,就可以看到成果了